package com.rich.dmr.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rich.dmr.R;
import com.rich.dmr.service.DmrService;
import com.rich.dmr.ui.activity.DialingActivity;
import com.rich.dmr.ui.activity.ListShowActivity;
import com.rich.dmr.ui.activity.SettingsActivity;
import com.rich.dmr.ui.view.SimpleToolbar;
import com.rich.dmr.utils.Constant;
import com.rich.dmr.utils.DataBaseUtils;
import com.rich.dmr.utils.Log;
import com.rich.dmr.utils.SoundPoolUtils;

import rich.dmr.DmrManager;

public class MainFragment extends Fragment implements View.OnClickListener, View.OnTouchListener {
    private String TAG = "rich---MainFragment";

    private DmrManager dmrManager;
    private SimpleToolbar simpleToolbar;
    private TextView tvContact;
    private TextView tvCallType;
    private Intent intent = new Intent();
    private SharedPreferences mSp;
    private boolean isHeadSet;
    private Context mContext;
    private float downX;
    private float downY;
    private long currentMS;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                if (dmrManager != null) {
                    if (isHeadSet) {
                        dmrManager.setHeadSetMic(1);
                    }
                    dmrManager.sendDmrPTT(true);
                    // dmrManager.sendSms(3,1000,"你好?adsds4455你好。。...你好?adsds4455你好。。...");
                }
            } else {
                if (dmrManager != null) {
                    if (isHeadSet) {
                        dmrManager.setHeadSetMic(2);
                    }
                    dmrManager.sendDmrPTT(false);
                }
            }
        }
    };

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        Log.d(TAG, "onAttach");
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        dmrManager = (DmrManager) mContext.getSystemService("dmrservice");

        mSp = mContext.getSharedPreferences(Constant.sp_key, Context.MODE_PRIVATE);
        boolean isCreate = mSp.getBoolean("createData", false);
        if (!isCreate) {
           /* DataBaseUtils.getInstance(mContext).insertChannel("Channel1", 409750000, 409750000);
            DataBaseUtils.getInstance(mContext).insertChannel("Channel2", 409500000, 409500000);
            DataBaseUtils.getInstance(mContext).insertChannel("Channel3", 409250000, 409250000);
            DataBaseUtils.getInstance(mContext).insertChannel("Channel5", 408750000, 408750000);
            DataBaseUtils.getInstance(mContext).insertChannel("Channel6", 406750000, 406750000);
            DataBaseUtils.getInstance(mContext).insertChannel("Channel8", 402000000, 402000000);

            DataBaseUtils.getInstance(mContext).insertGroupContact("Group1", 1000);
            DataBaseUtils.getInstance(mContext).insertGroupContact("Group2", 2000);
            DataBaseUtils.getInstance(mContext).insertGroupContact("Group3", 3000);
            DataBaseUtils.getInstance(mContext).insertGroupContact("Group5", 5000);
            DataBaseUtils.getInstance(mContext).insertGroupContact("Group6", 6000);
            DataBaseUtils.getInstance(mContext).insertGroupContact("Group8", 8000);

            DataBaseUtils.getInstance(mContext).insertRxList("Rx list1", "1000/2000/3000");
            DataBaseUtils.getInstance(mContext).insertRxList("Rx list2", "4000/5000/6000");
            DataBaseUtils.getInstance(mContext).insertRxList("Rx list3", "7000/8000/9000");
            DataBaseUtils.getInstance(mContext).insertRxList("Rx list5", "10000/20000/30000");
            DataBaseUtils.getInstance(mContext).insertRxList("Rx list6", "40000/50000/60000");
            DataBaseUtils.getInstance(mContext).insertRxList("Rx list8", "70000/80000/90000");
            SharedPreferences.Editor mEditor = mSp.edit();
            mEditor.putBoolean("createData", true);
            mEditor.apply();*/
        }

    }

    @SuppressLint({"WrongConstant", "ClickableViewAccessibility"})
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        View root = inflater.inflate(R.layout.fragment_main, container, false);
        simpleToolbar = root.findViewById(R.id.main_tools_bar);
        simpleToolbar.setLeftTitleClickListener(this);
        simpleToolbar.setLeftTitleDrawable(R.mipmap.rich_logo);
        simpleToolbar.setLeftTitleText(getString(R.string.telo_system));
        simpleToolbar.setLeftTextSize(25);
        LinearLayout mainMenu = root.findViewById(R.id.main_menu_settings);
        mainMenu.setOnClickListener(this);

        LinearLayout groupList = root.findViewById(R.id.main_group_list);
        groupList.setOnClickListener(this);

        LinearLayout singleCall = root.findViewById(R.id.main_single_call);
        singleCall.setOnClickListener(this);

        LinearLayout pttCall = root.findViewById(R.id.ptt_call_bt);
        pttCall.setOnClickListener(this);
        pttCall.setOnTouchListener(this);

        tvContact = root.findViewById(R.id.call_contact);
        tvCallType = root.findViewById(R.id.call_type);

        mSp = mContext.getSharedPreferences(Constant.sp_key, Context.MODE_PRIVATE);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_SET_COMMAND_STATE);
        intentFilter.addAction(Constant.ACTION_MODULE_STATE);
        intentFilter.addAction(Constant.ACTION_VERSION_INFO);
        intentFilter.addAction(Constant.ACTION_SIGNAL_INFO);
        intentFilter.addAction(Constant.ACTION_INBOUND_TYPE);
        intentFilter.addAction(Constant.ACTION_TRANSMITTER_LOCAL_ID);
        intentFilter.addAction(Constant.ACTION_INBOUND_NUMBER);
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);

        mContext.registerReceiver(broadcastReceiver, intentFilter);

        if (dmrManager != null) {
            //if (dmrManager.getMode() != 0) {
                dmrManager.setMode(0);
            //}
        }

        Intent intent = new Intent();
        intent.setClass(mContext, DmrService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
            mContext.startForegroundService(intent);
        }else {
            mContext.startService(intent);
        }

        return root;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_menu_settings:
                intent.setClass(mContext, SettingsActivity.class);
                startActivity(intent);
                break;
            case R.id.ptt_call_bt:

                break;
            case R.id.main_group_list:
                intent.setClass(mContext, ListShowActivity.class);
                startActivity(intent);
                break;
            case R.id.main_single_call:
                intent.setClass(mContext, DialingActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(0, 0);
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateInfo();
        Log.d(TAG, "onCreateView");
    }

    @SuppressLint("SetTextI18n")
    public void updateInfo() {
        boolean isShowId = mSp.getBoolean(Constant.showLocalId, true);
        if (dmrManager != null) {
            tvContact.setText(dmrManager.getTransmitContact() + "");
            switch (dmrManager.getContactType()) {
                case 0:
                    tvCallType.setText(getString(R.string.call_single));
                    break;
                case 1:
                    tvCallType.setText(getString(R.string.call_group));
                    break;
                case 2:
                    tvCallType.setText(getString(R.string.call_all));
                    break;
            }
            if (isShowId) {
                simpleToolbar.setRightTitleText(dmrManager.getLocalId() + "");
            } else {
                simpleToolbar.setRightTitleText("");
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mHandler.sendEmptyMessageDelayed(0, 150);
                downX = event.getX();
                downY = event.getY();
                currentMS = System.currentTimeMillis();
                Log.d(TAG, "onTouchEvent DOWN");
                return true;
            case MotionEvent.ACTION_MOVE:
                float moveX = event.getX() - downX;
                float moveY = event.getY() - downY;
                if (Math.abs(moveX) > 10 || Math.abs(moveY) > 10) {
                    Log.d(TAG, "onTouchEvent MOVE");
                    mHandler.removeMessages(0);
                }
                return true;
            case MotionEvent.ACTION_UP:
                long upTime = System.currentTimeMillis() - currentMS;
                Log.d(TAG, "upTime=" + upTime);
                if (upTime < 150) {
                    mHandler.removeMessages(0);
                    SoundPoolUtils.getInstance(mContext).playSoundErr();
                } else {
                    mHandler.removeMessages(0);
                    mHandler.sendEmptyMessage(1);
                }
                Log.d(TAG, "onTouchEvent UP");
                return true;
            case MotionEvent.ACTION_CANCEL:
                long cancelTime = System.currentTimeMillis() - currentMS;
                Log.d(TAG, "cancelTime=" + cancelTime);
                if (cancelTime < 150) {
                    mHandler.removeMessages(0);
                } else {
                    mHandler.removeMessages(0);
                    mHandler.sendEmptyMessage(1);
                }
                Log.d(TAG, "onTouchEvent CANCEL");
                return true;

        }
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mContext.unregisterReceiver(broadcastReceiver);
        Log.d(TAG, "onDestroy");
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent) {

            Log.d(TAG, "action=" + intent.getAction());

            if (Constant.ACTION_SET_COMMAND_STATE.equals(intent.getAction())) {
                //int setState = intent.getIntExtra(Constant.EXTRA_RESPONSE_DATA, -1);
            } else if (Constant.ACTION_MODULE_STATE.equals(intent.getAction())) {
                int moduleState = intent.getIntExtra(Constant.EXTRA_RESPONSE_DATA, -1);
                if (moduleState == 1) {
                    dmrManager.getDigitalVoiceInfo();
                } else if (moduleState == 2) {
                    updateInfo();
                } else if (moduleState == 3) {
                    //SoundPoolUtils.getInstance(mContext).playSound(true);
                } else if (moduleState == 4) {
                    updateInfo();
                    //SoundPoolUtils.getInstance(mContext).playSound(true);
                } else if (moduleState == 5) {
                    dmrManager.getSms();
                    SoundPoolUtils.getInstance(mContext).playSound(true);
                }
            } else if (Constant.ACTION_VERSION_INFO.equals(intent.getAction())) {

            } else if (Constant.ACTION_SIGNAL_INFO.equals(intent.getAction())) {

            } else if (Constant.ACTION_INBOUND_TYPE.equals(intent.getAction())) {
                int callType = intent.getIntExtra(Constant.EXTRA_RESPONSE_DATA, -1);
                mSp.edit().putInt("callType", callType).apply();
                switch (callType) {
                    case 0:
                        tvCallType.setText(getString(R.string.call_single));
                        break;
                    case 1:
                        tvCallType.setText(getString(R.string.call_group));
                        break;
                    case 2:
                        tvCallType.setText(getString(R.string.call_all));
                        break;
                }
            } else if (Constant.ACTION_TRANSMITTER_LOCAL_ID.equals(intent.getAction())) {
                int localId = intent.getIntExtra(Constant.EXTRA_RESPONSE_DATA, -1);
                int type = mSp.getInt("callType", -1);
                if (type == 0) {
                    tvContact.setText(localId + "");
                }
            } else if (Constant.ACTION_INBOUND_NUMBER.equals(intent.getAction())) {
                int contact = intent.getIntExtra(Constant.EXTRA_RESPONSE_DATA, -1);
                int type = mSp.getInt("callType", -1);
                if (type == 1 || type == 2) {
                    tvContact.setText(contact + "");
                }

            } else if (Constant.ACTION_DMR_SMS.equals(intent.getAction())) {
                int callType = intent.getIntExtra(Constant.EXTRA_SMS_TYPE, -1);
                int contact = intent.getIntExtra(Constant.EXTRA_SMS_CONTACT_TYPE, -1);
                String content = intent.getStringExtra(Constant.EXTRA_SMS_CONTENT);
                Toast.makeText(mContext, "callType=" + callType + " contact=" + contact + " content=" + content, Toast.LENGTH_SHORT).show();

            } else if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
                if (1 == intent.getIntExtra("state", 0)) {
                    isHeadSet = true;
                } else if (0 == intent.getIntExtra("state", 0)) {
                    isHeadSet = false;
                }
                Log.d(TAG, "isHeadSet=" + isHeadSet);
            }
        }
    };

}
